import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { TArticle } from 'src/entities/article.entity';

export class ArticleRepository {
  constructor(
    @InjectRepository(TArticle)
    private articleRepository: Repository<TArticle>,
  ) {}

  // 获取文章列表
  async queryRepository() {
    return await this.articleRepository.find({
      where: {
        delFlag: 0,
      },
    });
  }

  // 获取文章列表(单条)
  async queryOneRepository(id: number) {
    return await this.articleRepository.findOne({
      where: {
        id,
        delFlag: 0,
      },
    });
  }

  // 获取已发布的文章列表
  queryPublishedRepository() {
    return this.articleRepository.find({
      where: {
        delFlag: 0,
        status: 'published',
      },
    });
  }

  // 获取阅读量前6的文章
  async queryTop6ArticleRepository() {
    return await this.articleRepository.find({
      where: { delFlag: 0, status: 'published' },
      order: { views: 'DESC' },
      take: 6,
    });
  }

  // 添加文章
  async addRepository(articleDTO: TArticle) {
    const article = this.articleRepository.create(articleDTO);
    return await this.articleRepository.save(article);
  }

  // 更新文章
  async updateRepository(id: number, article: TArticle) {
    return await this.articleRepository.update(id, article);
  }

  // 发布文章
  async publishedArticleRepository(id: number, article: any) {
    return this.articleRepository.update(id, article);
  }

  // 删除文章
  async deleteRepository(id: number, deletedAt: string) {
    return this.articleRepository.update(id, { delFlag: 1, deletedAt });
  }
}
